package com.itmake.sample.toolbox.ip;

import org.lionsoul.ip2region.xdb.Searcher;

/**
 * 离线解析 ip 获取地址
 * <a href="https://github.com/lionsoul2014/ip2region/blob/master/data/ip2region.xdb">ip2region.xdb</a>
 *
 * @author Amjacks
 * @since 2023/08/10
 */
public class Ip2Region {

    /**
     * 根据 ip 地址解析出地址
     * @param ip ip 地址
     * @return 地址
     */
    public String getAddressByIp(String ip) {
        String path = "src\\main\\resources\\ip2region.xdb";
        Searcher searcher = null;
        try {
            // 加载 xdb
            byte[] cBuff = Searcher.loadContentFromFile(path);
            // 创建查询对象
            searcher = Searcher.newWithBuffer(cBuff);
            // 解析
            return searcher.search(ip);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        String ip = "43.155.130.130";
        Ip2Region ip2Region = new Ip2Region();
        String location = ip2Region.getAddressByIp(ip);
        System.out.println(location);
    }
}
